package com.txd.mofa.shouye.fgt;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.kongzue.baseframework.interfaces.Layout;
import com.kongzue.baseframework.util.JumpParameter;
import com.kongzue.baseframework.util.OnJumpResponseListener;
import com.kongzue.baseframework.util.Preferences;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.ResponseListener;
import com.kongzue.baseokhttp.util.Parameter;
import com.ninetaildemonfox.zdl.ninetails.map.JSONUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.txd.mofa.R;
import com.txd.mofa.adapter.ShouyeAdapter;
import com.txd.mofa.adapter.StaggeredGridAdapter;
import com.txd.mofa.base.BaseFgt;
import com.txd.mofa.bean.FlagBean;
import com.txd.mofa.bean.ShaixuanBean;
import com.txd.mofa.bean.ShouyeBean;
import com.txd.mofa.bean.ZhuangtaiBean;
import com.txd.mofa.fabu.aty.FabuAty;
import com.txd.mofa.login.BangdingAty;
import com.txd.mofa.login.StartAty;
import com.txd.mofa.net.NetUtils;
import com.txd.mofa.shouye.aty.XiangqingAtyTwo;
import com.txd.mofa.view.ShanchuDialog;
import com.wang.avi.AVLoadingIndicatorView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;



@Layout(R.layout.fgt_faxing)
public class FaxingFgt extends BaseFgt {

    RecyclerView recy;
    private StaggeredGridAdapter adapter;
    private List<ShaixuanBean> list = new ArrayList<>();
    private ShouyeAdapter shouyeAdapter;
    private String tit_id;
    private SmartRefreshLayout refreshLayout;
    private int page = 1;
    private ArrayList<Map<String, String>> data;
    private LinearLayout ll_net;
    private AVLoadingIndicatorView avi;
    private NestedScrollView sc;

    public static FaxingFgt newInstance(String s, String s1, String tit_id) {

        Bundle args = new Bundle();
        args.putString("s", s);
        args.putString("s1", s1);
        args.putString("tit_id", tit_id);
        FaxingFgt fragment = new FaxingFgt();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void initViews() {
        super.initViews();

        EventBus.getDefault().register(this);

        sc = findViewById(R.id.sc);
        ll_net = findViewById(R.id.ll_net);
        avi = findViewById(R.id.avi);
        refreshLayout = findViewById(R.id.refreshLayout);
        recy = findViewById(R.id.recy);

        StaggeredGridLayoutManager layout = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        recy.setLayoutManager(layout);

        String s = getArguments().getString("s");
        String s1 = getArguments().getString("s1");
        tit_id = getArguments().getString("tit_id");


        shouyeAdapter = new ShouyeAdapter(R.layout.item_shouye);

        recy.setAdapter(shouyeAdapter);

        recy.setNestedScrollingEnabled(false);

        sc.scrollTo(0,0);

        avi.show();


        http();

//        getUserAgent();



    }

    private  static String getUserAgent(){
        String userAgent = "";
        StringBuffer sb = new StringBuffer();
        userAgent = System.getProperty("http.agent");//Dalvik/2.1.0 (Linux; U; Android 6.0.1; vivo X9L Build/MMB29M)

        for (int i = 0, length = userAgent.length(); i < length; i++) {
            char c = userAgent.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", (int) c));
            } else {
                sb.append(c);
            }
        }

        Log.v("User-Agent","User-Agent: "+ sb.toString());
        return sb.toString();
    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {
        ll_net.setVisibility(View.GONE);
        refreshLayout.setVisibility(View.VISIBLE);
        http();
    }

    @Override
    protected void onNetworkDisConnected() {


        if (flag == false) {
            ll_net.setVisibility(View.VISIBLE);
            refreshLayout.setVisibility(View.GONE);
        }

    }



    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void flag11(FlagBean flagBean) {

        Log.e("pos",flagBean.getFlag());

        sc.smoothScrollTo(0, 0);
        recy.smoothScrollToPosition(0);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void zhuangtai(ZhuangtaiBean zhuangtaiBean) {

        List<Map<String, String>> data = shouyeAdapter.getData();

        data.get(zhuangtaiBean.getPos()).put("qiehuan",zhuangtaiBean.getQie());
        data.get(zhuangtaiBean.getPos()).put("collect",zhuangtaiBean.getSc());

        shouyeAdapter.notifyDataSetChanged();

    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    public void shaixuan(ShouyeBean shouyeBean) {

        crowd_id = shouyeBean.getRenqun();
        face_id = shouyeBean.getLian();
        length_id = shouyeBean.getChang();

        http();
    }


    private String crowd_id = "";
    private String face_id = "";
    private String length_id = "";

    private void http() {
        HttpRequest.POST(me, hairList, new Parameter().add("token", token)
                .add("title_id", tit_id)
                .add("crowd_id", crowd_id)
                .add("face_id", face_id)
                .add("length_id", length_id)
                .add("page", page), new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                if (error == null) {
                    avi.hide();
                    refreshLayout.finishLoadMore();
                    refreshLayout.finishRefresh();
                    Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                    if (map.get("code").equals("1")) {
                        data = JSONUtils.parseKeyAndValueToMapList(map.get("data"));
                        if (page == 1) {
                            for (int i = 0; i < data.size(); i++) {
                                data.get(i).put("qiehuan","222");
                            }
                            if (data.size() == 0){
                                shouyeAdapter.setEmptyView(getView);
                            }
                            shouyeAdapter.setNewData(data);
                        } else {
                            if (data == null) {
                                return;
                            }
                            for (int i = 0; i < data.size(); i++) {
                                data.get(i).put("qiehuan","222");
                            }
                            shouyeAdapter.addData(data);
                        }

                    }
                } else {
                    avi.hide();
                    toast("网络异常");
                }
            }
        });
    }

    @Override
    public void onLazyLoad() {

//        http();
    }

    @Override
    public void setEvents() {

//        ll_net.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (flag) {
//                    ll_net.setVisibility(View.GONE);
//                    refreshLayout.setVisibility(View.VISIBLE);
//                    http();
//                }
//            }
//        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (NetUtils.isNetworkAvailable(me)) {
                    page = 1;
                    http();
                }else {
                    refreshLayout.finishRefresh();
                    Toast.makeText(me, "网络连接错误，请检查您的网络", Toast.LENGTH_SHORT).show();
                }
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (NetUtils.isNetworkAvailable(me)) {
                    page++;
                    http();
                }else {
                    refreshLayout.finishLoadMore();
                    Toast.makeText(me, "网络连接错误，请检查您的网络", Toast.LENGTH_SHORT).show();
                }
            }
        });

        shouyeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {


                Preferences.getInstance().set(me, "tit_id", "tit_id", tit_id);
                jump(XiangqingAtyTwo.class, new JumpParameter()
                        .put("crowd_id", crowd_id)
                        .put("face_id", face_id)
                        .put("length_id", length_id)
                        .put("tit_id", tit_id)
                        .put("page", page)
                        .put("zhi", shouyeAdapter.getData())
                        .put("pos", position), new OnJumpResponseListener() {
                    @Override
                    public void OnResponse(JumpParameter jumpParameter) {
//                        page = 1;
////                        http();
                    }
                });
            }
        });

        shouyeAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.iv_sc:

                        if (Preferences.getInstance().getString(me,"shouji","shouji").equals("")){
                            Intent intent = new Intent(me, BangdingAty.class);
                            intent.putExtra("name","绑定手机号");
                            me.startActivity(intent);
                        }else {

                            if (shouyeAdapter.getData().get(position).get("collect").equals("1")) {
                                ShanchuDialog shanchuDialog = new ShanchuDialog(me, "您确认要取消收藏？", new ShanchuDialog.SignListener() {
                                    @Override
                                    public void shanchu() {

                                        collectHttp(position);
                                    }
                                });
                                shanchuDialog.show();
                            } else {
                                collectHttp(position);
                            }
                        }
                        break;
                    case R.id.iv_qiehuan:
                        if (Preferences.getInstance().getString(me,"shouji","shouji").equals("")){
                            Intent intent = new Intent(me, BangdingAty.class);
                            intent.putExtra("name","绑定手机号");
                            me.startActivity(intent);
                        }else {
                            if (shouyeAdapter.getData().get(position).get("qiehuan").equals("111")) {
                                shouyeAdapter.getData().get(position).put("qiehuan", "222");
                                shouyeAdapter.getData().get(position).put("img", shouyeAdapter.getData().get(position).get("beifen"));
                                shouyeAdapter.notifyDataSetChanged();
                            } else {
                                if (Preferences.getInstance().getString(me, "face_img", "face_img").equals("")) {

                                    jump(FabuAty.class);

                                } else {
                                    shouyeAdapter.getData().get(position).put("beifen", shouyeAdapter.getData().get(position).get("img"));
                                    qiehuan(position);

                                }
                            }
                        }
                        break;
                }
            }
        });


    }

    private void qiehuan(int position) {
        avi.show();
        HttpRequest.POST(me, faceChang, new Parameter().add("token",token).add("hair_id",shouyeAdapter.getData().get(position).get("id"))
                .add("user_img_url",Preferences.getInstance().getString(me,"face_img","face_img")), new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                if (error == null) {
                    Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                    if (map.get("code").equals("1")){
                        Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));

                        avi.hide();

                        String fake_img_url = data.get("fake_img_url");

                        String fake_video_url = data.get("fake_video_url");

                        shouyeAdapter.getData().get(position).put("qiehuan","111");

                        shouyeAdapter.getData().get(position).put("img",fake_img_url);
                        shouyeAdapter.getData().get(position).put("video",fake_video_url);
                        shouyeAdapter.notifyDataSetChanged();


                    }else{
                        avi.hide();
                    }

                }else {
                    avi.hide();
                    toast("网络异常");
                }
            }
        });
    }

    private void collectHttp(int position) {
        HttpRequest.POST(me, isCollect, new Parameter().add("token", token).add("hair_id", shouyeAdapter.getData().get(position).get("id")), new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                if (error == null) {
                    Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                    if (map.get("code").equals("1")) {

                        if (shouyeAdapter.getData().get(position).get("collect").equals("1")) {
                            shouyeAdapter.getData().get(position).put("collect", "2");
                        } else {
                            shouyeAdapter.getData().get(position).put("collect", "1");
                        }
                        shouyeAdapter.notifyDataSetChanged();

                    }
                } else {
                    toast("网络异常");
                }
            }
        });
    }


}
